package com.jf.es.sql.jdbc;


import cn.hutool.db.Entity;
import cn.hutool.db.handler.EntityListHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;

@RestController
@RequestMapping("es/sql")
public class EsSqlController {

    @Autowired
    @Qualifier("EsDataSource")
    private DataSource esDataSource;

    @GetMapping
    public ResponseEntity<Object> execute(String sql) throws SQLException {
        try (Connection connection = esDataSource.getConnection();
             Statement statement = connection.createStatement();
             ResultSet results = statement.executeQuery(sql)) {
            final List<Entity> handle = EntityListHandler.create().handle(results);
            return ResponseEntity.ok(handle);
        }
    }
}
